package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ResultException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.sms.SMSSender;
import com.ruoyi.common.utils.sms.SendSmsUtils;
import com.ruoyi.system.domain.SmsValidateCode;
import com.ruoyi.system.mapper.SmsValidateCodeMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISmsValidateCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信验证码 服务层实现
 * 
 * @author njbjs
 * @date 2018-11-20
 */
@Service
public class SmsValidateCodeServiceImpl implements ISmsValidateCodeService {
    private static Logger logger = LoggerFactory.getLogger(SmsValidateCodeServiceImpl.class);
	@Autowired
	private SmsValidateCodeMapper smsValidateCodeMapper;
	@Autowired
    private SysUserMapper sysUserMapper;


	@Override
    @Transactional(rollbackFor = Exception.class)
	public int smsSend(String receiver, String vcode, String type,
					   long intervalDate, long expiryDate) throws ResultException {
        //先判断手机号码的正确性
        if (sysUserMapper.checkPhoneUnique(receiver) == null) {
            throw new ResultException("手机号码不存在");
        }

        //获取手机号是否已经发送验证
        SmsValidateCode smsValidateCode = smsValidateCodeMapper.selectByMobile(receiver, type);
        if (smsValidateCode != null) {
            //已经发送，且已失效
            if (DateUtils.pastSeconds(smsValidateCode.getCreateTime()) >= expiryDate) {
                //失效 可以发送
            } else {
                if (DateUtils.pastSeconds(smsValidateCode.getCreateTime()) >= intervalDate) {
                    //可以发送
                } else {
                    //不可以重复发送
                    logger.info("给【"+receiver+"】发送验证码失败：发送频率太快");
                    throw new ResultException("发送频率太快");
                }
            }
        }
        logger.info("正在给[{}]发送[{}]验证码[{}]", receiver, type, vcode);

        //删除已有的历史验证码
        if (smsValidateCode != null) {
            smsValidateCodeMapper.deleteByMobile(receiver, type);
        }

        //保存验证码进数据库
        smsValidateCode = new SmsValidateCode();
        smsValidateCode.setCreateTime(new Date());
        smsValidateCode.setVCode(vcode);
        smsValidateCode.setMobile(receiver);
        smsValidateCode.setType(type);
        smsValidateCodeMapper.insertSmsValidateCode(smsValidateCode);

        //把短信放到短信队列等待发送
        Map<String, String> map = new HashMap<>();
        map.put("vcode", vcode);
        map.put("type", SendSmsUtils.template_vcode);
        map.put("mobile", receiver);
        SMSSender smsSender = SMSSender.getInstance();
        smsSender.putInQueue(map);

        logger.info("给[{}]发送[{}]验证码[{}]，推送到队列成功", receiver, type, vcode);
        //发送成功
        return 1;
	}

	@Override
	public int validateCode(String receiver, String vcode, String type, long expiryDate) throws ResultException {
        //获取手机号是否已经发送验证
        logger.info("校验给[{}]发送的[{}]验证码[{}]", receiver, type, vcode);
        SmsValidateCode smsValidateCode = smsValidateCodeMapper.selectByMobileAndVcode(receiver, type, vcode);
        if (smsValidateCode != null) {
            //已经发送
            if (DateUtils.pastSeconds(smsValidateCode.getCreateTime()) >= expiryDate) {
                //失效
                smsValidateCodeMapper.deleteByMobile(receiver, type);
                return Constants.SMS_VALIDATE_RESULT_OUTOFDATE;
            } else {
                //正常
                smsValidateCodeMapper.deleteByMobile(receiver, type);
                return Constants.SMS_VALIDATE_RESULT_SUCCESS;
            }
        }
        //没有验证码，即验证码不正确
        return Constants.SMS_VALIDATE_RESULT_NOTEXIST;
	}
}
